package com.zhouyibike.uu.ui.activity.mybike;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.LoopPagerAdapter;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.ProductDetailResult;
import com.zhouyibike.uu.entity.ProductPayTypeResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.mybike.Imagesee.ImagePagerActivity;
import com.zhouyibike.uu.ui.activity.mybike.Imagesee.ImagePagerActivity2;
import com.zhouyibike.uu.ui.adapter.BuydanchetypeAdapter;
import com.zhouyibike.uu.ui.adapter.RengoudancheAdapter;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.MyGridListView;
import com.zhouyibike.uu.utils.DataSingle;
import com.zhouyibike.uu.utils.TextUtils;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RengouActivity extends BaseActivity {
    private RollPagerView mRollViewPager;
    private ArrayList<String> bannerPictureURLs = new ArrayList<>();
    private ListView lv;
    private RengoudancheAdapter adapter;
    private ImageButton mBtnBack;
    private TextView mBtnTitle,roll_yuanjia;
    private LinearLayout scrollly;
    private TextView nametv, pricetv, numtv, textView2;
    private BottomSheetDialog bottomInterPasswordDialog;
    private ImageView iv_codedialog_dismis, buydancheiv;
    private TextView jiatv, jiantv, buydanchetitle, buydanchebt,total_pricetv;
    private EditText sellingedit;
    private int sellingnum = 0;
    private MyGridListView gv;
    private BuydanchetypeAdapter adapter2;
    private ArrayList<ProductPayTypeResult.DataBean.PayTypesBean> payTypeslist = new ArrayList<>();
    private Dialog xxdialog;
    private int buytype = 0;
    private ProductPayTypeResult chuandiProductPayTypeResult;
    private double moneycount = 0;
    private int yiquancount = 0;
    private List<ProductDetailResult.DataBean.ContentImagesBean> imgs=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rengou);
        initView();
        getMsg();
        setDialog();
        initListener();
    }

    private void setDialog() {
        LayoutInflater inflater = LayoutInflater.from(RengouActivity.this);
        final View headview = inflater.inflate(R.layout.rengou_show_dialog, lv, false);
        buydanchebt = (TextView) headview.findViewById(R.id.buydanchebt);
        jiantv = (TextView) headview.findViewById(R.id.buydanchejian);
        jiatv = (TextView) headview.findViewById(R.id.buydanchejia);
        total_pricetv= (TextView) headview.findViewById(R.id.total_pricetv);
        buydancheiv = (ImageView) headview.findViewById(R.id.buydancheiv);
        buydanchetitle = (TextView) headview.findViewById(R.id.buydanchetitle);
        gv = (MyGridListView) headview.findViewById(R.id.gv);
        jiantv.setEnabled(false);
        sellingedit = (EditText) headview.findViewById(R.id.buydanchenum);
        sellingedit.addTextChangedListener(new RengouActivity.EditTextWatcher());
        jiatv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sellingnum += 1;
                sellingedit.setText(sellingnum + "");
            }
        });
        jiantv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sellingnum -= 1;
                sellingedit.setText(sellingnum + "");
            }
        });
        iv_codedialog_dismis = (ImageView) headview.findViewById(R.id.iv_codedialog_dismis);
//        bottomInterPasswordDialog = new BottomSheetDialog(RengouActivity.this);
//        bottomInterPasswordDialog.setContentView(headview);
//        bottomInterPasswordDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//        final BottomSheetBehavior  bottomSheetBehavior = BottomSheetBehavior.from((View) headview.getParent());
//        bottomInterPasswordDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
//            }
//        });
//        bottomInterPasswordDialog.setCancelable(true);
//        bottomInterPasswordDialog
//                .contentView(headview)
//                .heightParam(1000)
//                .inDuration(500)
//                .outDuration(500)
//                .inInterpolator(new BounceInterpolator())
//                .outInterpolator(new AnticipateInterpolator())
//                .cancelable(true);
        xxdialog = new Dialog(this, R.style.Dialog_Fullscreen);
        xxdialog.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        Window dialogWindow = xxdialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        // lp.width = DataSingle.getInstance().PhoneW; // 宽度
        // lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setAttributes(lp);
    }

    private void initListener() {
       lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
               if (i==0)
               {
                   return;
               }
               if (imgs!=null&&imgs.size()>0) {
                   Intent intent = new Intent(RengouActivity.this, ImagePagerActivity.class);
                   // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
                   intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, (Serializable) imgs);
                   intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, i - 1);
                   startActivity(intent);
               }}
       });
        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        iv_codedialog_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (xxdialog.isShowing()) {
                    xxdialog.dismiss();
                }
            }
        });
        textView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                xxdialog.show();
            }
        });
        buydanchebt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (buytype == 0 && sellingnum == 0) {
                    toastShow("请选择购买数量和方式");
                } else if (sellingnum == 0) {
                    toastShow("请选择购买数量");
                } else if (buytype == 0) {
                    toastShow("请选择购买方式");
                } else {
                    Intent i = new Intent(RengouActivity.this, RengoujiesuanActivity.class);
                    i.putExtra("bikeinfo", chuandiProductPayTypeResult);
                    i.putExtra("buytype", buytype);
                    i.putExtra("buycount", sellingnum);
                    i.putExtra("buyonemoney", moneycount);
                    i.putExtra("buyoneyiquan", yiquancount);
                    startActivityForResult(i,888);
                }

            }
        });
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                buytype = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(position)).getPayTypeId();
                moneycount = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(position)).getMoney();
                yiquancount = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(position)).getYiQuan();
                adapter2.setchecked(position);
                setmoneytotal();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 888 && resultCode == 1) {
            if (xxdialog.isShowing()) {
                xxdialog.dismiss();
            }
            getmountMsg();
        }
        if (requestCode == 888 && resultCode == 2) {
            if (xxdialog.isShowing()) {
                xxdialog.dismiss();
            }
            setResult(789);
           finish();
        }
    }

    private void initView() {
        lv = (ListView) findViewById(R.id.rengoudanche_lv);
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("商品详情");
//        mBtnTitle.setTextColor(Color.BLUE);
//        mBtnTitle.getPaint().setColor(Color.WHITE);
//        mBtnTitle.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //UNDERLINE_TEXT_FLAG下划线删除线STRIKE_THRU_TEXT_FLAG
        mBtnTitle.getPaint().setAntiAlias(true);//抗锯齿
        textView2 = (TextView) findViewById(R.id.textView2);

    }

    /**
     * //获取商品详情
     */
    private void getMsg() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.ProductDetail(params),
                new ApiCallback<ProductDetailResult>() {
                    @Override
                    public void onSuccess(ProductDetailResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            bannerPictureURLs.clear();
                          //  mBtnTitle.setText(model.getData().getTitle());
                            for (int i = 0; i < model.getData().getBannars().size(); i++) {
                                bannerPictureURLs.add(model.getData().getBannars().get(i).getImagePath());
                            }
                            //配置适配器
                            imgs.clear();
                            imgs= model.getData().getContentImages();
                            adapter = new RengoudancheAdapter(RengouActivity.this, model.getData().getContentImages());
                            //  View headview=View.inflate(this,R.layout.lunbo_view,lv);
                            LayoutInflater inflater = LayoutInflater.from(RengouActivity.this);
                            View headview = inflater.inflate(R.layout.lunbo_view, lv, false);
                            scrollly = (LinearLayout) headview.findViewById(R.id.roll_goumaifangshi);
                            roll_yuanjia=headview.findViewById(R.id.roll_yuanjia);
                            roll_yuanjia.setText( "￥"+model.getData().getdiscountedPrice()+" ");
                            roll_yuanjia.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //UNDERLINE_TEXT_FLAG下划线删除线STRIKE_THRU_TEXT_FLAG
                            roll_yuanjia.getPaint().setAntiAlias(true);//抗锯齿
                            nametv = (TextView) headview.findViewById(R.id.roll_name);
                            nametv.setText(model.getData().getContent());
                            numtv = (TextView) headview.findViewById(R.id.roll_xiaoliang);
                            numtv.setText("销量:" + model.getData().getAmount() + "辆");
                            pricetv = (TextView) headview.findViewById(R.id.roll_jiage);
                            pricetv.setText("￥" + model.getData().getPrice());
                            mRollViewPager = (RollPagerView) headview.findViewById(R.id.roll_view_pager);
                            double scyle = 0;
                            if (model.getData().getBannars() != null && model.getData().getBannars().size() > 0) {
                                scyle = Double.parseDouble(model.getData().getBannars().get(0).getHeight()) / Double.parseDouble(model.getData().getBannars().get(0).getWidth());
                            } else {
                                scyle = 0.6284444444444445;
                                //1.5912305516265912;
                            }
                            mRollViewPager.setLayoutParams(new AppBarLayout.LayoutParams(DataSingle.getInstance().PhoneW, (int) (DataSingle.getInstance().PhoneW * scyle)));
                            mRollViewPager.setPlayDelay(5000);
                            mRollViewPager.setAnimationDurtion(500);
                            mRollViewPager.setAdapter(new TestLoopAdapter(mRollViewPager)); //设置适配器
                            mRollViewPager.setHintView(new ColorPointHintView(RengouActivity.this, getResources().getColor(R.color.color_normal), Color.WHITE));// 设置圆点指示器颜色
                            // mRollViewPager.setHintView(new IconHintView(this, R.drawable.point_focus, R.drawable.point_normal));
                            lv.addHeaderView(headview);
                            lv.setAdapter(adapter);
                            scrollly.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    xxdialog.show();
                                }
                            });
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        getMsg2();
                    }
                });
    }
    private void getmountMsg() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
//        showProgressDialog();
        addSubscription(apiStores.ProductDetail(params),
                new ApiCallback<ProductDetailResult>() {
                    @Override
                    public void onSuccess(ProductDetailResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            numtv.setText("销量:" + model.getData().getAmount() + "辆");
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    /**
     * //获取商品支付方式
     */
    private void getMsg2() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.ProductPayType(params),
                new ApiCallback<ProductPayTypeResult>() {
                    @Override
                    public void onSuccess(ProductPayTypeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            chuandiProductPayTypeResult = model;
                            payTypeslist.clear();
                            buydanchetitle.setText(model.getData().getContent());
//                            .memoryPolicy(MemoryPolicy.NO_CACHE,MemoryPolicy.NO_STORE)
                          //  Picasso.with(RengouActivity.this).load(model.getData().getProductImg()).error(R.drawable.zhanweitu).placeholder(R.drawable.zhanweitu).into(buydancheiv);
                            Picasso.with(RengouActivity.this).load(model.getData().getProductImg()).error(R.drawable.zhanweitu).placeholder(R.drawable.zhanweitu)
                                    .networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE) .into(buydancheiv);
                            payTypeslist = (ArrayList<ProductPayTypeResult.DataBean.PayTypesBean>) model.getData().getPayTypes();
                         //   payTypeslist.addAll(payTypeslist);
                            adapter2 = new BuydanchetypeAdapter(RengouActivity.this, payTypeslist);
                            gv.setAdapter(adapter2);
                        } else {
                            toastShow(model.getMessage());
                        }

                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                        setoncheck();
                    }
                });
    }

    private class TestLoopAdapter extends LoopPagerAdapter {
        // private int[] imgs = {R.drawable.img0, R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4,};  // 本地图片
        private int count = bannerPictureURLs.size(); // banner上图片的数量

        public TestLoopAdapter(RollPagerView viewPager) {
            super(viewPager);
        }

        @Override
        public View getView(ViewGroup container, int position) {
            final int picNo = position ;
            ImageView view = new ImageView(container.getContext());
            //   view.setImageResource(imgs[position]);
            view.setScaleType(ImageView.ScaleType.FIT_XY);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//            Picasso.with(RengouActivity.this).load(bannerPictureURLs.get(position)).placeholder(R.drawable.zhanweitu).error(R.drawable.zhanweitu).into(view);  // 加载网络图片
            Picasso.with(RengouActivity.this).load(bannerPictureURLs.get(position)).placeholder(R.drawable.zhanweitu).error(R.drawable.zhanweitu).networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
                .into(view);  // 加载网络图片
            view.setOnClickListener(new View.OnClickListener()      // 点击事件
            {
                @Override
                public void onClick(View v)
                {
                    if (bannerPictureURLs!=null&&bannerPictureURLs.size()>0)
                    {
                    Intent intent = new Intent(RengouActivity.this, ImagePagerActivity2.class);
                    intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, (bannerPictureURLs));
                    intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX,picNo);
                    startActivity(intent);
                }}

            });

            return view;
        }

        @Override
        public int getRealCount() {
            return count;
        }

    }

    class EditTextWatcher implements TextWatcher {

        public void afterTextChanged(Editable edt) {
            if (TextUtils.isNullorEmpty(sellingedit.getText().toString())) {
                jiantv.setEnabled(false);
                jiatv.setEnabled(false);
                sellingnum = 0;
            } else {
                jiatv.setEnabled(true);
                if (Integer.parseInt(sellingedit.getText().toString()) == 0) {
                    jiantv.setEnabled(false);
                } else {
                    jiantv.setEnabled(true);
                }
                sellingnum = Integer.parseInt(sellingedit.getText().toString());
            }
            sellingedit.setSelection(edt.length());//将光标移至文字末尾
            setmoneytotal();
        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

    }
    private void setmoneytotal(){
//        total_pricetv.setText("￥"+(Double) (sellingnum*moneycount));
        if (yiquancount!=0&&moneycount==0){
            total_pricetv.setText("翼券"+sellingnum*yiquancount);
        }else if (yiquancount!=0&&moneycount!=0){
//            total_pricetv.setText("￥"+df.format((Double) (sellingnum*moneycount))+"+"+"翼券"+sellingnum*yiquancount);
            total_pricetv.setText("￥" + (Double) (sellingnum * moneycount) + "+" + "翼券" + sellingnum * yiquancount);
            // holder.tv.setText("￥"+1111+"+"+"翼券"+100);
        }else{
//            total_pricetv.setText("￥"+df.format((Double) (sellingnum*moneycount)));
            total_pricetv.setText("￥"+(Double) (sellingnum*moneycount));
        }
    }
    private void setoncheck(){
        if (payTypeslist!=null&&payTypeslist.size()>0)
        {
            sellingnum=1;
            jiantv.setEnabled(true);
            jiatv.setEnabled(true);
            sellingedit.setText(sellingnum+"");
            buytype = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(0)).getPayTypeId();
            moneycount = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(0)).getMoney();
            yiquancount = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(0)).getYiQuan();
            adapter2.setchecked(0);
            setmoneytotal();
        }
    }
    DecimalFormat df = new DecimalFormat("######0.00");
}
